<template>
    <div class="app-container">
        <el-form :model="queryParams" ref="queryParams" :inline="true" v-show="showSearch" label-width="68px">
            <el-form-item label="批次号" prop="batchNum">
                <el-date-picker :editable="false" clearable size="small" v-model="queryParams.batchNum" type="date"
                    value-format="yyyyMMdd" format="yyyyMMdd" placeholder="请选择">
                </el-date-picker>
            </el-form-item>
            <el-form-item label="产品名称" prop="productId">
                <el-input v-model="queryParams.productId" placeholder="输入产品名称"> </el-input>
            </el-form-item>

            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
                    v-hasPermi="['Productionline:firstconfirm:add']">新增</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple"
                    @click="handleDelete" v-hasPermi="['Productionline:firstconfirm:delete']">删除</el-button>
            </el-col>
            <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="firstconfirm" @selection-change="handleSelectionChange" max-height="550">
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column label="批次号" align="center" prop="batchNum">
                <template slot-scope="scope">
                    <span style="color:rgba(213, 241, 255, 0.8)">{{ scope.row.batchNum || '- -' }}</span>
                </template>
            </el-table-column>
            <el-table-column label="产品名称" align="center" prop="productName">
                <template slot-scope="scope">
                    <span style="color:rgba(213, 241, 255, 0.8)">{{ scope.row.productName || '- -' }}</span>
                </template>
            </el-table-column>
            <!-- <el-table-column label="创建时间" align="center" prop="createTime">
                <template slot-scope="scope">
                    <span style="color:rgba(213, 241, 255, 0.8)">{{ scope.row.createTime || '- -' }}</span>
                </template>
            </el-table-column> -->
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                <template slot-scope="scope">
                    <el-button size="mini" type="text" icon="el-icon-bottom" @click="excelhandleView(scope.row)"
                        v-hasPermi="['Productionline:firstconfirm:export']">导出</el-button>
                    <el-button v-hasPermi="['Productionline:firstconfirm:query']" size="mini" type="text"
                        icon="el-icon-view" @click="handleView(scope.row,'查看')">查看</el-button>
                    <el-button size="mini" type="text" icon="el-icon-edit" @click="handleView(scope.row,'修改')"
                        v-hasPermi="['Productionline:firstconfirm:edit']" >修改</el-button>
                    <el-button size="mini" style="margin-left: 10px;" type="text" icon="el-icon-circle-check"
                        slot="reference" v-hasPermi="['Productionline:firstconfirm:verify']" v-if="scope.row.status ==1"
                        @click="handleView(scope.row,'审批')">审批</el-button>
                    <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                        v-hasPermi="['Productionline:firstconfirm:delete']">删除</el-button>


                </template>
            </el-table-column>
        </el-table>

        <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize" @pagination="getList" />

        <!-- 添加或修改仰口生产报对话框 -->
        <!--  <el-dialog fullscreen :title="title" :visible.sync="open" width="900px" append-to-body> -->
        <el-dialog fullscreen :title="title" :visible.sync="open" width="900px" append-to-body custom-class="myDialog">
            <TableHeader2 :data="{
                mainTitle: '首件确认单',
                company: '',
                code: '',
            }" />
            <el-form ref="form" :model="form" :rules="rules" label-width="90px" class="safetyRecord_form">
                <el-row :gutter="20">
                    <el-col :span="6">
                        <el-form-item label="产品名称" prop="productId">
                            <Dialog @dialogChange="dialogChange($event)" :echoValue="form.productName" parameter="rows"
                                value="id" label="name" :multiple="false" search="name/code"
                                url="/basic/productInfo/listSelect" :column="['产成品编号/code', '产成品名称/name']"
                                placeholder="请选择内容" :axiosData="{ typeCode: 'YYTRKQS' }" :openDisabled="openDisabled" />
                            <!-- <el-input v-model="form.productId" placeholder="请输入产品名称" :disabled="openDisabled" /> -->
                        </el-form-item>
                    </el-col>
                    <el-col :span="6" :offset="12">
                        <el-form-item label="批次号" prop="batchNum">
                            <el-date-picker :editable="false" clearable size="small" v-model="form.batchNum" type="date"
                                value-format="yyyyMMdd" format="yyyyMMdd" placeholder="请选择" :disabled="openDisabled">
                            </el-date-picker>
                        </el-form-item>
                    </el-col>
                </el-row>
                <br />
                <el-divider content-position="center">首件确认单子信息</el-divider>
                <el-table class="noGao" :data="subList" border style="width: 100%;margin-top: 30px;">
                    <el-table-column width="100" align="center" prop="order" label="项目序号"></el-table-column>
                    <el-table-column align="center" prop="name" label="检查项目">
                    </el-table-column>
                    <el-table-column minWidth="500" align="center" prop="record" label="检查记录">
                        <template slot-scope="scope">
                            <treeselect v-if="scope.row.type==2" v-model="scope.row.record" :disable-branch-nodes="true"
                                :options="treeselectData" :limit="3" placeholder="请选择" :normalizer="normalizer"
                                :searchable="false" :appendToBody="true" z-index="9999" multiple
                                :disabled="openDisabled||scope.row.pkName!=nickName||title=='审批首件确认单'" collapse-tags
                                show-count />

                            <el-input v-else :disabled="openDisabled" v-model="scope.row.record" placeholder="请输入">
                            </el-input>
                        </template>
                    </el-table-column>
                    <el-table-column minWidth="190" align="center" prop="pkName" label="品控人员">
                        <template slot-scope="scope">
                            <el-input :disabled="openDisabled||scope.row.pkName!=nickName||title=='审批首件确认单'"
                                v-model="scope.row.pkName" placeholder="请输入">
                            </el-input>
                        </template>
                    </el-table-column>
                    <el-table-column minWidth="190" align="center" prop="pkResult" label="审核结果">
                        <template slot-scope="scope">
                            <el-select :disabled="openDisabled||scope.row.pkName!=nickName||title=='审批首件确认单'"
                                v-model="scope.row.pkResult" placeholder="请选择">
                                <el-option label="合格" :value="1">
                                </el-option>
                                <el-option label="不合格" :value="0">
                                </el-option>
                            </el-select>
                        </template>
                    </el-table-column>
                    <el-table-column minWidth="190" align="center" prop="pkRemark" label="审核意见">
                        <template slot-scope="scope">
                            <el-input :disabled="openDisabled||scope.row.pkName!=nickName||title=='审批首件确认单'"
                                v-model="scope.row.pkRemark" placeholder="请输入" type="textarea">
                            </el-input>
                        </template>
                    </el-table-column>
                    <el-table-column v-if="form.status!=0" minWidth="190" align="center"
                        prop="leaderName" label="生产班长/主管">
                        <template slot-scope="scope">
                            <el-input :disabled="openDisabled" v-model="scope.row.leaderName"
                                placeholder="请输入">
                            </el-input>
                        </template>
                    </el-table-column>
                    <el-table-column v-if="form.status!=0" minWidth="190" align="center"
                        prop="leaderResult" label="审核结果">
                        <template slot-scope="scope">
                            <el-select :disabled="openDisabled" v-model="scope.row.leaderResult" placeholder="请选择">
                                <el-option label="合格" :value="1">
                                </el-option>
                                <el-option label="不合格" :value="0">
                                </el-option>
                            </el-select>
                        </template>
                    </el-table-column>
                    <el-table-column v-if="form.status!=0" minWidth="190" align="center"
                        prop="leaderRemark" label="审核意见">
                        <template slot-scope="scope">
                            <el-input :disabled="openDisabled" v-model="scope.row.leaderRemark" placeholder="请输入"
                                type="textarea">
                            </el-input>
                        </template>
                    </el-table-column>
                </el-table>

            </el-form>
            <div slot="footer" class="dialog-footer" v-if="!openDisabled">
                <el-button type="primary" @click="submitForm" :disabled="btn_loading">确 定</el-button>
                <el-button @click="cancel">取 消</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>

    import lodash from 'lodash';
    import {
        listFirstconfirm,
        getFirstconfirm,
        delFirstconfirm,
        verifyFirstconfirm,
        addFirstconfirm,
        updateFirstconfirm,
    } from "@/api/quality/productionline/confirm";
    import $axios from "axios";
    import TableHeader2 from "@/components/table/tableData/header2.vue";
    import JSON from './json.js'
    import { getInfo } from "@/api/login";
    import { listSelect2 } from "@/api/report/process/label";
    import { listUser } from "@/api/system/user";
    import Treeselect from "@riophae/vue-treeselect";
    import "@riophae/vue-treeselect/dist/vue-treeselect.css";
    export default {
        components: { TableHeader2, Treeselect },
        name: "Confirm",
        data() {
            return {
                nickName: null,
                //弹窗是否禁止编辑
                openDisabled: true,
                //树状图数据
                treeselectData: [],
                //树状图平铺数据
                pingtData: [],
                // 遮罩层
                loading: false,
                //添加修改按钮状态
                btn_loading: false,
                // 选中数组
                ids: [],
                // 非单个禁用
                single: true,
                // 非多个禁用
                multiple: true,
                // 显示搜索条件
                showSearch: true,
                // 总条数
                total: 0,
                // 首件确认单格数据
                firstconfirm: [],
                // 弹出层标题
                title: "",
                // 是否显示弹出层
                open: false,
                // 查询参数
                queryParams: {
                    pageNum: 1,
                    pageSize: 50,
                    batchNum: null,
                    productName: null,
                },
                // 表单参数
                form: {
                    status: 0,
                },
                subList: [],
                // 表单校验
                rules: {
                    productId: [{ required: true, message: "不能为空" }],
                    batchNum: [{ required: true, message: "不能为空" }],
                }
            };
        },
        created() {
            this.getListfac();
            this.queryUserList()
            // 二次处理数据
            this.subList = lodash.cloneDeep(JSON)
            this.getList();
        },
        methods: {
            /* 查询用户列表 */
            queryUserList() {
                getInfo().then((response) => {
                    this.nickName = response.user.nickName;
                });
            },
            getListfac() {
                listSelect2().then((response) => {
                    this.treeselectData = response.rows;
                    this.pingData = this.flat(response.rows)
                });
            },
            //平铺
            /**
             * 递归平铺转为一维数组
             * @param {*} treeNode 传进来的值，可以是数组 可以是一个对象
             * @param {*} childKey 树形结构 children
             * @returns
             */
            flat(treeNode, childKey = "children") {

                //判断传进来是数组还是对象 如果是数组[...数组]，浅拷贝 操作不影响原来数组，如果是对象把它变为数组
                const nodes = Array.isArray(treeNode) ? [...treeNode] : [treeNode];
                const result = [];
                nodes.forEach((node) => {
                    result.push(node);
                    if (Array.isArray(node[childKey])) {
                        // node[childKey].forEach((_node) =>
                        //   result.push(...flat(_node, childKey))
                        // ); //第一种写法 递归平铺
                        //第二种写法 (简洁) 如同[1,2,3,...[4,5,6]] = [1,2,3,4,5,6]
                        result.push(...this.flat(node[childKey], childKey));
                    }
                });
                return result;
            },
            /** 转换数据结构 */
            normalizer(node) {
                if (node.children && !node.children.length) {
                    delete node.children;
                }
                return {
                    id: node.id,
                    label: node.label,
                    children: node.children,
                };
            },
            dialogChange(event) {
                this.$set(this.form, 'productId', event.value)
                this.$set(this.form, 'productName', event.label)
            },
            /** 查询仰口生产报列表 */
            getList() {
                this.loading = true;
                listFirstconfirm(this.queryParams).then((response) => {
                    if (response.code == 200) {
                        this.firstconfirm = response.rows;
                        this.total = response.total;
                        this.loading = false;
                    } else {
                        this.$message.error('列表加载失败');
                    }
                }).catch((err) => {
                    this.loading = false;
                    // this.$message.error('列表加载失败')
                });
                // $axios({
                //     method: 'get',
                //     url: '/zyk/firstconfirm/list',
                //     params: this.queryParams, // 请求参数拼接在url上
                // }).then(({ data }) => {
                //     //请求成功，触发then中的函数
                //     this.loading = false;
                //     if (data.code == 200) {
                //         this.firstconfirm = data.rows;
                //         this.total = data.total;

                //     } else {
                //         this.$message.error('列表加载失败');
                //     }
                // }).catch((err) => {
                //     this.loading = false;
                //     this.$message.error('列表加载失败')
                // });

            },

            // 取消按钮
            cancel() {
                this.open = false;
                this.reset();
            },
            // 表单重置
            reset() {
                this.form = {
                    batchNum: null,
                    productName: null,
                };
                this.resetForm("form");
            },
            /** 搜索按钮操作 */
            handleQuery() {
                this.queryParams.pageNum = 1;
                this.getList();
            },
            /** 重置按钮操作 */
            resetQuery() {
                // this.resetForm("queryParams");
                this.queryParams = {
                    batchNum: null,
                    productName: null,
                    pageNum: 1,
                    pageSize: 50,
                };
                this.handleQuery();
            },
            // 多选框选中数据
            handleSelectionChange(selection) {
                this.ids = selection.map((item) => item.id);
                this.single = selection.length !== 1;
                this.multiple = !selection.length;
            },
            /** 新增按钮操作 */
            handleAdd() {
                this.reset();
                this.openDisabled = false;
                this.open = true;
                this.form.status = 0
                this.subList = lodash.cloneDeep(JSON)
                for (let i in this.subList) {
                    this.$set(this.subList[i], 'pkName', this.nickName)
                }
                this.title = "添加首件确认单";
            },

            /** 查看按钮 */
            handleView(row, bel) {
                this.reset();
                this.openDisabled = bel == '查看' ? true : false;
                this.title = `${bel}首件确认单`;
                const id = row.id || this.ids;
                // $axios({
                //     method: 'get',
                //     url: '/zyk/firstconfirm/' + id,

                // }).then(({ data }) => {
                //     this.btn_loading = false
                //     if (data.code == 200) {
                //         this.open = true;
                //         this.form = data.data
                //         let subList = data.data.subList
                //         this.subList = lodash.cloneDeep(JSON)
                //         for (let items of this.subList) {
                //             for (let item of subList) {
                //                 if (items.key == item.key) {
                //                     items.recordName = item.recordName
                //                     items.pkName = item.pkName
                //                     items.pkResult = item.pkResult
                //                     items.pkRemark = item.pkRemark
                //                     items.leaderName = item.leaderName
                //                     items.leaderResult = item.leaderResult
                //                     items.leaderRemark = item.leaderRemark
                //                     if (items.type == 2) {
                //                         items.record = item.record.split(',')
                //                         items.recordName = item.recordName.split(',')
                //                     } else {
                //                         items.record = item.record
                //                     }
                //                     if (bel == '审批') {
                //                         items.leaderName = this.nickName
                //                     }

                //                 }
                //             }
                //         }
                //         console.log(this.subList)
                //         this.$forceUpdate()
                //     }
                // }).catch((err) => {
                //     console.log(err)
                //     this.$message.error('查询失败');
                // })


                getFirstconfirm(id).then((response) => {
                    this.btn_loading = false
                    if (response.code == 200) {
                        this.open = true;
                        this.form = response.data
                        let subList = response.data.subList
                        this.subList = lodash.cloneDeep(JSON)
                        for (let items of this.subList) {
                            for (let item of subList) {
                                if (items.key == item.key) {
                                    items.recordName = item.recordName
                                    items.pkName = item.pkName
                                    items.pkResult = item.pkResult
                                    items.pkRemark = item.pkRemark
                                    items.leaderName = item.leaderName
                                    items.leaderResult = item.leaderResult
                                    items.leaderRemark = item.leaderRemark
                                    if (items.type == 2) {
                                        items.record = item.record.split(',')
                                    } else {
                                        items.record = item.record
                                    }
                                    if (bel == '审批') {
                                        items.leaderName = this.nickName
                                    }
                                }
                            }
                        }
                        this.$forceUpdate()
                    } else {
                        this.$message.error('查询失败');
                    }
                }).catch((err) => {
                    // this.$message.error('查询失败');
                })
            },
            /** 提交按钮 */
            submitForm() {
                this.$refs["form"].validate((valid) => {
                    if (valid) {
                        var subList = lodash.cloneDeep(this.subList)

                        for (let item of subList) {
                            if (item.type == 2) {
                                item.recordName = []
                                if (item.record.length == 0) {
                                    return (this.$message.closeAll(), this.$message.error(`请填写${item.name}的检查记录`))
                                }
                                for (let it of item.record) {
                                    for (let items of this.pingData) {
                                        if (items.id == it) {

                                            item.recordName.push(items.label);
                                        }
                                    }
                                }
                            } else {
                                if (item.record == '') {
                                    return (this.$message.closeAll(), this.$message.error(`请填写${item.name}的检查记录`))
                                }
                            }
                        }

                        for (let item of subList) {
                            if (item.type == 2) {
                                item.record = item.record.toString();
                                item.recordName = item.recordName.toString();
                            }

                        }

                        this.btn_loading = true
                        this.form.subList = lodash.cloneDeep(subList)
                        if (this.form.id != null) {

                            if (this.title == "审批首件确认单") {
                                verifyFirstconfirm(this.form).then((response) => {
                                    this.open = false;
                                    this.btn_loading = false
                                    if (response.code == 200) {
                                        this.getList();
                                        this.msgSuccess("审批成功");
                                    } else {
                                        this.$message.error('审批失败');
                                    }
                                }).catch((err) => {
                                    this.btn_loading = false
                                    // this.$message.error('审批失败');
                                })

                                // $axios.post('/zyk/firstconfirm/verify', this.form).then(({ data }) => {
                                //     //请求成功，触发then中的函数
                                //     this.open = false;
                                //     this.btn_loading = false
                                //     if (data.code == 200) {
                                //         this.msgSuccess("审批成功");

                                //         this.getList();
                                //     } else {
                                //         this.btn_loading = false
                                //         this.$message.error('审批失败');
                                //     }

                                // }).catch(error =>
                                //     //请求失败，触发catch中的函数 可省略
                                //     this.$message.error('保存失败')
                                // )
                            } else {
                                updateFirstconfirm(this.form).then((response) => {
                                    this.open = false;
                                    this.btn_loading = false
                                    if (response.code == 200) {
                                        this.getList();
                                        this.msgSuccess("修改成功");
                                    } else {
                                        this.$message.error('修改失败');
                                    }
                                }).catch((err) => {
                                    this.btn_loading = false
                                    // this.$message.error('修改失败');
                                })

                                // $axios.put('/zyk/firstconfirm', this.form).then(({ data }) => {
                                //     //请求成功，触发then中的函数
                                //     this.open = false;
                                //     this.btn_loading = false
                                //     if (data.code == 200) {
                                //         this.msgSuccess("修改成功");

                                //         this.getList();
                                //     } else {
                                //         this.btn_loading = false
                                //         this.$message.error('修改失败');
                                //     }

                                // }).catch(error =>
                                //     //请求失败，触发catch中的函数 可省略
                                //     this.$message.error('保存失败')
                                // )
                            }
                        } else {
                            try {
                                this.form.id = undefined
                            } catch (error) {

                            }


                            addFirstconfirm(this.form).then((response) => {
                                this.btn_loading = false
                                this.open = false;
                                if (response.code == 200) {
                                    this.getList();
                                    this.msgSuccess("新增成功");
                                } else {
                                    this.$message.error('新增失败');
                                }
                            }).catch((err) => {
                                this.btn_loading = false
                                // this.$message.error('新增失败')
                            });




                            // $axios.post('/zyk/firstconfirm', this.form).then(({ data }) => {
                            //     //请求成功，触发then中的函数
                            //     this.open = false;
                            //     this.btn_loading = false
                            //     if (data.code == 200) {
                            //         this.msgSuccess("新增成功");

                            //         this.getList();
                            //     } else {
                            //         this.btn_loading = false
                            //         this.$message.error('新增失败');
                            //     }

                            // }).catch(error =>
                            //     //请求失败，触发catch中的函数 可省略
                            //     this.$message.error('保存失败')
                            // )
                        }
                    }
                });
            },
            /** 删除按钮操作 */
            handleDelete(row) {
                const ids = row.id || this.ids;
                this.$confirm(
                    '是否确认删除选中的的数据项?',
                    "警告",
                    {
                        confirmButtonText: "确定",
                        cancelButtonText: "取消",
                        type: "warning",
                    }
                )
                    .then(() => {
                        delFirstconfirm(ids).then((response) => {
                            if (response.code == 200) {
                                this.getList();
                                this.msgSuccess("删除成功");
                            } else {
                                this.$message.error('删除失败');
                            }
                        }).catch((err) => {

                            // this.$message.error('删除失败')
                        });

                        // $axios({
                        //     method: 'delete',
                        //     url: '/zyk/firstconfirm/' + ids,

                        // }).then(res => {
                        //     this.getList();
                        //     this.msgSuccess("删除成功");

                        // })
                    })
                    .catch((err) => {
                        console.log(err)
                    });
            },

            //审批
            handleVerify(row) {
                let obj = {
                    id: row.id,
                    fzr: this.nickName
                }
                verifyFirstconfirm(obj).then((response) => {
                    if (response.code == 200) {
                        this.getList();
                        this.msgSuccess("审批成功");
                    } else {
                        this.$message.error('审批失败');
                    }
                }).catch((err) => {

                    // this.$message.error('审批失败')
                });


                // $axios.post('/zyk/Firstconfirm/verify/' + row.id).then(({ data }) => {
                //     //请求成功，触发then中的函数
                //     if (data.code == 200) {
                //         this.msgSuccess("审批成功");

                //         this.getList();
                //     } else {
                //         this.$message.error('审批失败');
                //     }

                // }).catch(error =>
                //     //请求失败，触发catch中的函数 可省略
                //     this.$message.error('审批失败')
                // )
            },
            /** 导出按钮操作 */
            excelhandleView(row) {
                this.download(
                    "Laboratory/firstconfirm/exportexcel?id=" + row.id,
                    {
                        ...this.queryParams,
                    },
                    "每日首件确认单" + this.parseTime(new Date()) + ".xlsx"
                );
                // const headers = { 'Content-Type': 'application/x-www-form-urlencoded' };
                // $axios.post('/zyk/firstconfirm/exportexcel?id=' + row.id, {
                //     ...this.queryParams,
                // }, {
                //     headers,
                //     timeout: 60000,
                //     responseType: 'blob'
                // }).then(({ data }) => {
                //     console.log(data)
                //     let filename = "每日首件确认单" + this.parseTime(new Date()) + ".xlsx"
                //     //请求成功，触发then中的函数
                //     const content = data
                //     const blob = new Blob([content])
                //     console.log(blob)
                //     if ('download' in document.createElement('a')) {
                //         const elink = document.createElement('a')
                //         elink.download = filename
                //         elink.style.display = 'none'
                //         elink.href = URL.createObjectURL(blob)
                //         document.body.appendChild(elink)
                //         elink.click()
                //         URL.revokeObjectURL(elink.href)
                //         document.body.removeChild(elink)
                //     } else {
                //         navigator.msSaveBlob(blob, filename)
                //     }


                // }).catch((err) => {
                //     console.log(err)
                // })
            },

        },
    };
</script>
<style>
    .myDialog .safetyRecord_form .el-form-item {
        border: none !important;
    }
</style>
<style lang="scss">
    .noGao {
        .el-table__body tr:hover>td {
            background-color: #0a366d !important;
            color: rgba(213, 241, 255, 0.8) !important;
        }
    }

    .vue-treeselect__limit-tip {
        margin-top: -10px;
    }
</style>